package com.yc.forum.servlet;

import com.yc.forum.dao.UserDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
@MultipartConfig(
        maxFileSize = 1024*1024+10,
        maxRequestSize = 1024*1024*30,
        fileSizeThreshold = 0,//小：内存，大：硬盘
        location = ""
)
public class RegisterServlet extends HttpServlet {
    @Override
    //注册
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("================================RegisterServlet========================");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        UserDao userDao=new UserDao();
        String phone=request.getParameter("regist_phone");
        if (userDao.queryRegisterAccount(phone)){
            response.getWriter().write("该账号已注册");
        }else{
            Part file=request.getPart("file");
            System.out.println("file大小============="+file.getSize());
            //地址
            String path;
            String filename="head_img"+phone+System.currentTimeMillis()+".jpg";
            if (file.getSize() != 0) {
                //获得ServletContext对象
                ServletContext servletContext = this.getServletContext();
                //保存路径
                path = servletContext.getRealPath("head_img")+"/";
                System.out.println(path);
                path=path+filename;
                System.out.println(path);
                file.write((path));
                //读取路径
                path="head_img"+"\\"+filename;
            }else {
                path=null;
            }
            String name=request.getParameter("regist_name");
            String pwd=request.getParameter("regist_pwd");
            String realname=request.getParameter("regist_realname");
            String sex=request.getParameter("regist_sex");
            String age=request.getParameter("regist_age");
            String e_mail=request.getParameter("regist_e-mail");
            userDao.register(phone,name,path,pwd,realname,sex,age,e_mail);
            response.getWriter().write("注册成功");
        }
    }
}
